package com.xiaotao.utils;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

public class JWTUtil {
//    @Resource
//    private static StringRedisTemplate stringRedisTemplate;
    private static final String secretString = "token!Q2W#E$RWtoken!Q2W#E$RWtoken!Q2W#E$RW";
    //生成jwt
    public static String getToken(Map map) throws JOSEException {
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT).build();
        Payload payload = new Payload(map);
        //3.签名  签名的长度不能太短
        JWSSigner macSigner = new MACSigner(secretString);
        //通过   base64(头)+base(载荷) + 签名
        JWSObject jwsObject = new JWSObject(header, payload);
        jwsObject.sign(macSigner);
        String jwt = jwsObject.serialize();
//        stringRedisTemplate.opsForValue().set("token",jwt,20,TimeUnit.SECONDS);
        return jwt;

    }
    public static boolean verifyToken(String token) throws JOSEException, ParseException {
//        if(stringRedisTemplate.opsForValue().get("token")!=null){
//            JWSObject jwsObject = JWSObject.parse(token);
//            JWSVerifier verifier = new MACVerifier("token!Q2W#E$RWtoken!Q2W#E$RWtoken!Q2W#E$RW");
//            boolean verify = jwsObject.verify(verifier);
//            return verify;
//
//        }else {
//            boolean verify = false;
//            return verify;
//        }
        JWSObject jwsObject = JWSObject.parse(token);
        JWSVerifier verifier = new MACVerifier("token!Q2W#E$RWtoken!Q2W#E$RWtoken!Q2W#E$RW");
        //验证jwt
        boolean verify = jwsObject.verify(verifier);
        return verify;
    }
    public static Map getPayload(String token) throws ParseException {
        JWSObject jwsObject = JWSObject.parse(token);
        Payload payload = jwsObject.getPayload();
        Map<String, Object> jsonObject = payload.toJSONObject();
        return jsonObject;
    }

    //从token中获取当前用户的登录信息
    public  static Integer getUserId(String token) throws ParseException {
        JWSObject parse = JWSObject.parse(token);
        Payload payload = parse.getPayload();
        Map<String ,Object> jsonObject = payload.toJSONObject();
        Integer userId = Integer.parseInt(jsonObject.get("id").toString());
        return userId;

    }
}






























